package com.dwyinyuan.producer;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.concurrent.BlockingQueue;

public class WallHavenProducer implements Runnable {

    private String name;
    private BlockingQueue<String> blockingQueue;

    public WallHavenProducer(String name, BlockingQueue<String> blockingQueue) {
        this.name = name;
        this.blockingQueue = blockingQueue;
    }

    @Override
    public void run() {
        Document doc = null;
        try {
            for (int i = 1; i < 5; i++) {
                System.out.println("current page:" + i);
                System.out.println("-----------------------------------");
//                doc = Jsoup.connect("https://alpha.wallhaven.cc/latest?page=" + i).get(); //爬取首页使用
                doc = Jsoup.connect("https://wallhaven.cc/search?categories=001&purity=000&sorting=date_added&order=desc&page=" + i).get();

                //爬取首页使用
/*                Elements sections = doc.getElementsByClass("sm-thumb");
                for (Element ele : sections) {
                    String src = ele.getElementsByTag("img").attr("src");
                    String[] split = src.split("/");
                    String f = "https://w.wallhaven.cc/full/%s/wallhaven-%s";
                    String full_url = String.format(f, split[4], split[5]);
                    blockingQueue.put(full_url);
                    System.out.println(name + " put " + full_url);
                }*/

                Element div = doc.getElementById("thumbs");
                Elements sections = div.getElementsByTag("section");
                for (Element ele : sections) {
                    Elements links = ele.getElementsByTag("img");
                    for (Element e : links) {
                        String src = e.attr("data-src");
                        String[] split = src.split("/");
                        String f = "https://w.wallhaven.cc/full/%s/wallhaven-%s";
                        String full_url = String.format(f, split[4], split[5]);
                        blockingQueue.put(full_url);
                        System.out.println(name + " put " + full_url);
                    }
                }
            }

            //消费者根据""退出while循环
            blockingQueue.put("");
            System.out.println("-----------------------------------");
            System.out.println(name + " is over");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}
